import { Injectable, NotFoundException } from '@nestjs/common';
import { Article as ArticleItem } from './interface/article.interface';
import { ArticleCreateDTO } from './dto/article-create.dto';
import { ArticleEditDTO } from './dto/article-edit.dto';
import { IdDTO } from './dto/id.dto';
import { ListDTO } from './dto/list.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Article } from './entity/article.entity';
import { getPagination } from 'src/utils';

@Injectable()
export class ArticleService {
  list: ArticleItem[];

  constructor(
    @InjectRepository(Article)
    private readonly articleRepository: Repository<Article>,
  ) {
    this.list = [];
  }
  async getMore(listDTO: ListDTO) {
    const { page = 1, pageSize = 10 } = listDTO;
    const getList = this.articleRepository
      .createQueryBuilder('article')
      .where({ isDelete: false })
      .leftJoin('article.tags', 'tag')
      .select([
        'article.id',
        'article.title',
        'article.description',
        'article.createTime',
        'article.updateTime',
      ])
      .addSelect(['tag.id', 'tag.label'])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    const [list, total] = await getList;
    const pagination = getPagination(total, pageSize, page);
    return { list, pagination };
  }

  async getMoreByTagId(listDTO: ListDTO) {
    const { page = 1, pageSize = 10, tagId } = listDTO;

    const getList = this.articleRepository
      .createQueryBuilder('article')
      .where({ isDelete: false })
      .andWhere('tag.id = :tagId', { id: tagId })
      .andWhere('tag.isDelete = :isDelete', { isDelete: false })
      .leftJoin('article.tags', 'tag')
      .select([
        'article.id',
        'article.title',
        'article.description',
        'article.createTime',
        'article.updateTime',
      ])
      .addSelect(['tag.id', 'tag.label'])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    const [list, total] = await getList;
    const pagination = getPagination(total, pageSize, page);
    return { list, pagination };
  }
  async getOne(idDto: IdDTO) {
    const { id } = idDto;
    const articleDetail = await this.articleRepository
      .createQueryBuilder('article')
      .where('article.id = :id', { id })
      .leftJoin('article.tags', 'tag')
      .select([
        'article.id',
        'article.title',
        'article.description',
        'article.createTime',
        'article.updateTime',
      ])
      .addSelect(['tag.id', 'tag.label'])
      .getOne();
    if (!articleDetail) {
      throw new NotFoundException('Article not found');
    }

    return articleDetail;
  }
  async create(articleCreateDTO: ArticleCreateDTO) {
    const article = new Article();
    article.title = articleCreateDTO.title;
    article.description = articleCreateDTO.description;
    article.content = articleCreateDTO.content;
    const result = await this.articleRepository.save(article);
    return result;
  }
  async update(articleEditDTO: ArticleEditDTO) {
    const article = new Article();
    const oldArticle = await this.articleRepository.findOneBy({
      id: articleEditDTO.id,
    });
    if (!oldArticle) {
      throw new NotFoundException('文章不存在');
    }
    article.id = articleEditDTO.id;
    article.title = articleEditDTO.title || oldArticle.title;
    article.description = articleEditDTO.description || oldArticle.description;
    article.content = articleEditDTO.content || oldArticle.content;
    const result = await this.articleRepository.save(article);
    return result;
  }
  async delete(idDTO: IdDTO) {
    const { id } = idDTO;
    const article = await this.articleRepository.findOneBy({ id });
    if (!article) {
      throw new NotFoundException('Article not found');
    }
    article.isDelete = true;
    return await this.articleRepository.save(article);
  }
}
